import React from "react";
import FieldContext from "./FormContext";

// https://github.com/react-component/field-form/blob/master/src/Field.tsx
class Field extends React.Component<any, any, any> {
  public static contextType = FieldContext;

  public getControlled = (childProps: any = {}) => {
    const { name } = this.props;
    const { getFieldValue, setFieldValue } = this.props.fieldContext;
    // 给props增加属性
    return {
      ...childProps,
      // ...mergedGetValueProps(value)
      value: getFieldValue(name),
      onChange: (event: any) => {
        // setFieldValue({ [name]: event.target.value });
        setFieldValue(name, event.target.value);
      },
    };
  };

  public render() {
    const { children } = this.props;
    let returnChildNode: React.ReactNode;
    returnChildNode = React.cloneElement(
      children,
      this.getControlled((children as React.ReactElement).props)
    );
    return returnChildNode;
  }
}

function WrapperField<Values = any>({ name, ...restProps }: any) {
  const fieldContext = React.useContext(FieldContext);
  return <Field name={name} {...restProps} fieldContext={fieldContext} />;
}

export default WrapperField;
